<route lang="json5">
{
  style: {
    navigationBarTitleText: '首页',
  },
}
</route>
<template>
  <view class="bg-white overflow-hidden">
    <button @click="reSearch">扫描蓝牙</button>
    <button @click="onPrint">打印</button>
    <button @click="onPrintBarCode">打印条形码</button>
    <button @click="onPrintQrCode">打印二维码</button>
    <button @click="onPrintRpeat">循环打印</button>
    <button @click="onPrintImg">打印图片</button>
    <canvas
      class="imgCanvas"
      canvas-id="imgCanvas"
      :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"
    ></canvas>

    <wd-cell-group>
      <wd-cell
        v-for="(item, index) in blueDeviceList"
        :key="index"
        @click="handleConnect(item)"
        clickable
        :title="item.deviceName"
      ></wd-cell>
    </wd-cell-group>
  </view>
</template>

<script lang="ts" setup>
import {
  closeBluetoothAdapter,
  getBluetoothDevicesList,
  connectBluetoothDevice,
} from '@/utils/print/bluetooth'
import { usePrint } from '@/hooks/usePrint'
import { ref, getCurrentInstance } from 'vue'

// 获得当前组件实例
const instance = getCurrentInstance()

interface BlueDeviceItem {
  deviceName: string
  deviceId: string
  /** 0:未连接、1:已连接、2:连接中 */
  status: 0 | 1 | 2
}

// 蓝牙设备的id
const deviceId = ref('')
const serviceId = ref('')
const characteristicId = ref('')
const blueDeviceList = ref<BlueDeviceItem[]>([])

const {
  onPrint,
  onPrintBarCode,
  onPrintQrCode,
  onPrintRpeat,
  onPrintImg,
  canvasWidth,
  canvasHeight,
} = usePrint({
  deviceId,
  serviceId,
  characteristicId,
  instance,
})

/** 重新搜索蓝牙设备 */
function reSearch() {
  closeBluetoothAdapter().then(() => {
    // 获取蓝牙列表
    getDeviceList()
  })
}

/** 获取蓝牙列表 */
function getDeviceList(loadingText?: string) {
  uni.showLoading({
    title: loadingText || '搜索蓝牙设备',
    mask: true,
  })
  getBluetoothDevicesList()
    .then((result: UniApp.BluetoothDeviceInfo[]) => {
      uni.hideLoading()
      blueDeviceList.value = []
      console.log('获取蓝牙列表', result)
      result.forEach((item) => {
        if (item.name && item.name !== '未知设备') {
          blueDeviceList.value.push({
            deviceName: item.name,
            deviceId: item.deviceId,
            status: 0,
          })
        }
      })
    })
    .catch((err) => {
      console.log(err)

      uni.showToast({
        title: '获取蓝牙列表失败',
        icon: 'none',
      })
      blueDeviceList.value = []
    })
}

/** 处理选中蓝牙操作 */
function handleConnect(data: BlueDeviceItem) {
  uni.showToast({
    title: '有设备连接中，请耐心等待',
    icon: 'none',
    mask: true,
  })
  if (data.status !== 1) {
    const blueDevice = blueDeviceList.value.find((item) => item.deviceId === data.deviceId)
    if (blueDevice) {
      blueDevice.status = 2
    }
    connectDevice(data.deviceId)
  }
}

/**
 * 连接蓝牙设备
 * @param _deviceId 蓝牙设备id
 */
async function connectDevice(_deviceId: string) {
  connectBluetoothDevice(_deviceId)
    .then((result) => {
      uni.showToast({
        title: '连接成功',
        icon: 'none',
      })
      const blueDevice = blueDeviceList.value.find((item) => item.deviceId === _deviceId)
      if (blueDevice) {
        blueDevice.status = 1
      }
      const { serviceId: _serviceId, characteristicId: _characteristicId } = result
      deviceId.value = _deviceId
      serviceId.value = _serviceId
      characteristicId.value = _characteristicId
    })
    .catch((err) => {
      console.log(err)

      uni.showToast({
        title: '连接失败',
        icon: 'none',
      })
      const blueDevice = blueDeviceList.value.find((item) => item.deviceId === _deviceId)
      if (blueDevice) {
        blueDevice.status = 0
      }
      deviceId.value = ''
      serviceId.value = ''
      characteristicId.value = ''
    })
}
</script>

<style></style>
